package com.yl.nettylearning.netty.day12;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @author yangl
 */
public class MessageClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端接收到消息：");
        System.out.println("服务器发送的消息长度：" + len);
        System.out.println("服务器发送的消息内容：" + new String(content, CharsetUtil.UTF_8));
        System.out.println("客户端接收到的消息数量：" + (++this.count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //发送10条数据，今天杭州下雪了，西湖好多人
        for (int i = 0; i < 10; i++) {
            String msg = "今天杭州下雪了，西湖好多人" + i;
            byte[] content = msg.getBytes(Charset.forName("utf-8"));
            int length = msg.getBytes(CharsetUtil.UTF_8).length;
            //创建协议包
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(content);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("错误信息：" + cause.getMessage());
        ctx.close();
    }
}
